import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:flutter_base/user/app_user_manager.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
// import 'package:uuid/uuid.dart';
import 'package:crypto/crypto.dart';

class RequestInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _setRequestHeaders(options);
    handler.next(options);
    logWrite("${options.uri.toString()}\n${options.data}");
  }

  @override
  Future onError(DioException err, ErrorInterceptorHandler handler) async {
    super.onError(err, handler);
    logWrite("${err.requestOptions.uri.toString()}\n$err");
  }

  _setRequestHeaders(RequestOptions options) {
    Map<String, dynamic> header = {
      'accept': 'application/json',
      'token': AppUserManager().token,
    };
    // header.addAll(_getSignatureHeader());
    if (options.headers.isNotEmpty) {
      options.headers.forEach((key, value) => header[key] = value);
    }
    options.headers = header;
  }

  // static Map<String, Object> _getSignatureHeader({bool needSignature = true}) {
  //   var headers = {
  //     "app-name": "aiwan",
  //     'os': Platform.operatingSystem,
  //     'app-vrn': AppConfig.version,
  //     'timestamp': DateTime.now().millisecondsSinceEpoch ~/ 1000,
  //     "chnl-name": AppConfig.appChannel,
  //     // "nonce": const Uuid().v4(),
  //   };
  //   if (needSignature) {
  //     var keys = headers.keys.toList();
  //     keys.sort();
  //     StringBuffer stringBuffer = StringBuffer();
  //     for (String k in keys) {
  //       stringBuffer.write(headers[k]);
  //     }
  //     stringBuffer.write(AppConfig.headerSecretKey);
  //     String signature = md5.convert(utf8.encode(stringBuffer.toString())).toString();
  //     headers["signature"] = signature;
  //   }
  //   return headers;
  // }
}
